package com.example.mxs.util;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalControllerAdvice {

    /**
     * 处理 Exception 异常
     *
     * @param httpServletRequest httpServletRequest
     * @param e                  异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseData exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
        ResponseData responseData=new ResponseData();
        String message=e.getMessage();

        if (e instanceof NoHandlerFoundException) {
            responseData.setMeta(MetaData.CODE_404);
        }else if(message.equals("用户不存在，请重新登录")){
            responseData.setMeta(MetaData.CODE_404);
        }else if(message.equals("无token，请重新登录")){
            responseData.setMeta(MetaData.CODE_401);
        }else{
            responseData.setMeta(MetaData.CODE_404);
        }
        return responseData;
    }

}
